package repository

import (
	"errors"
	"github.com/jinzhu/gorm"
	"go_shengshu_admin/model"
	"go_shengshu_admin/query"
	"go_shengshu_admin/utils"
	"time"
)

type OrderRepository struct {
	DB *gorm.DB
}

type OrderRepoInterface interface {
	List(req *query.ListQuery) (orders []*model.Order, err error)
	GetTotal() (total int64, err error)
	GetOrder(order model.Order) (*model.Order, error)
	Exist(id string) *model.Order
	Add(order model.Order) *model.Order
	Edit(order model.Order) (bool, error)
	Delete(id string) (bool, error)
}

func (repo *OrderRepository) List(req *query.ListQuery) (orders []*model.Order, err error) {
	db := repo.DB
	limit, offset := utils.Page(req.PageSize, req.Page)
	if err := db.Order(utils.Sort(req.Order)).Limit(limit).Offset(offset).Find(&orders).Error; err != nil {
		return nil, err
	}
	return orders, nil
}

func (repo *OrderRepository) GetTotal() (total int64, err error) {
	var orders []model.Order
	db := repo.DB
	if err := db.Find(&orders).Count(&total).Error; err != nil {
		return 0, err
	}
	return total, err
}

func (repo *OrderRepository) GetOrder(order model.Order) (*model.Order, error) {
	if err := repo.DB.Where(&order).Find(&order).Error; err != nil {
		return nil, err
	}
	return &order, nil
}

func (repo *OrderRepository) Exist(id string) *model.Order {
	var order *model.Order
	var count = 0
	repo.DB.Where("order_id = ?", id).Find(&order).Count(&count)
	if count > 0 {
		return order
	}
	return nil
}

func (repo *OrderRepository) Add(order model.Order) *model.Order {
	order.CreateAt, _ = time.Parse(utils.TimeLayout, utils.GetNow())
	order.UpdateAt, _ = time.Parse(utils.TimeLayout, utils.GetNow())
	if err := repo.DB.Create(&order).Error; err != nil {
		return nil
	}
	return &order
}

func (repo *OrderRepository) Edit(order model.Order) (bool, error) {
	if repo.Exist(order.OrderId) == nil {
		return false, errors.New("订单不存在")
	}
	if err := repo.DB.Model(&order).Where("order_id = ?", order).Updates(map[string]interface{}{
		"nick_name": order.NickName, "mobile": order.Mobile, "total_price": order.TotalPrice,
		"order_status": order.OrderStatus, "extra_info": order.ExtraInfo, "UserAddress": order.UserAddress,
	}).Error; err != nil {
		return false, err
	}
	return true, nil
}

func (repo *OrderRepository) Delete(id string) (bool, error) {
	var order *model.Order
	if err := repo.DB.Model(&order).Where("order_id = ?", id).Update("is_deleted", true).Error; err != nil {
		return false, err
	}
	return true, nil
}
